#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include <arpa/inet.h>
#include <cstdio>
#include <unistd.h>
#include <netinet/in.h>

static void usage(char *myproc)
{
    std::cout << "usage: " << myproc << " ip"
              << " port" << std::endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        exit(1);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);
    // 创建套接字
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(2);
    }
    struct sockaddr_in peer;
    memset(&peer,'\0', sizeof(peer));
    peer.sin_family = AF_INET;
    peer.sin_port = htons(server_port);
    peer.sin_addr.s_addr = inet_addr(server_ip.c_str());
    // 连接套接字
    if (connect(sock, (struct sockaddr *)&peer, (socklen_t)sizeof(peer)) < 0)
    {
        std::cerr << "connect error" << std::endl;
        exit(3);
    }
    std::cout << "connect success" << std::endl;
    while (true)
    {
        std::string line;
        std::cout << "请输入# " << std::endl;
        getline(std::cin, line);
        if (line == "quit")
            break;
        ssize_t s = send(sock,line.c_str(),line.size(),0);
        if(s>0)
        {
            char buffer[1024];
            ssize_t s = recv(sock,buffer,sizeof(buffer)-1,0);
            if(s > 0)
            {
                buffer[s]=0;
                std::cout<<"回显#"<<buffer<<std::endl;
            }
            else if(s==0)
            {
                break;
            }
            else
            {
                break;
            }
        }
    }
    close(sock);
    return 0;
}